using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Web;
using Framework.Library.Core.Config;

namespace Framework.Library.Core.Utils
{
    public class GenerateCounter
    {
        private readonly string _cmd = string.Empty;
        private readonly Stopwatch _stopWatch = new Stopwatch();
        private readonly HttpContext current = HttpContext.Current;
        private string sessionName
        {
            get
            {
                return Configurations.PORTALID + "PageGenerate";
            }
        }

        public GenerateCounter()
        {
            if (Configurations.DEBUG_MODE)
            {
                _cmd = Configurations.FRAMEWORK;
                _stopWatch.Start();
            }
        }

        public GenerateCounter(string sql)
        {
            if (Configurations.DEBUG_MODE)
            {
                _cmd = sql;
                _stopWatch.Start();
            }
        }

        public static void Dispose()
        {
            if (Configurations.DEBUG_MODE)
            {
                if (HttpContext.Current != null)
                    HttpContext.Current.Session.Remove(Configurations.PORTALID + "PageGenerate");
            }
        }

        public void Reset()
        {
            if (Configurations.DEBUG_MODE)
            {
                _stopWatch.Stop();
                double duration = _stopWatch.ElapsedMilliseconds/1000.0;
                if (current != null)
                {
                    string _gen = String.Format("{0}: {1:N3} s", _cmd, duration);
                    List<string> lstCounter = new List<string>();
                    if (HttpContext.Current.Session != null)
                    {
                        if (HttpContext.Current.Session[sessionName] == null)
                        {
                            lstCounter.Add(_gen);
                            HttpContext.Current.Session[sessionName] = lstCounter;
                        }
                        else
                        {
                            lstCounter = (List<string>)HttpContext.Current.Session[sessionName];
                            lstCounter.Add(_gen);
                            HttpContext.Current.Session[sessionName] = lstCounter;
                        }
                    }
                }
                this._stopWatch.Reset();
            }
        }
    }
}